//
//  NativeAdsController.m
//  KKSDK
//
//  Created by jay Win on 2019/4/1.
//  Copyright © 2019 jay Win. All rights reserved.
//

#import "NativeAdsController.h"


@implementation NativeAdsController

- (void)request:(UIViewController *)rootViewController container:(UIView *)viewController{
    self.rootVC=rootViewController;
    self.viewContainner=viewController;
    
    MPStaticNativeAdRendererSettings *settings = [[MPStaticNativeAdRendererSettings alloc] init];
    
    settings.renderingViewClass = [MPStaticNativeAdView class];
    
    
    MPNativeAdRendererConfiguration *staticNativeConfig = [MPStaticNativeAdRenderer rendererConfigurationWithRendererSettings:settings];
    //设置原生广告池容量
    NSMutableArray * configurations = [NSMutableArray arrayWithCapacity:1];
    
    [configurations addObject:staticNativeConfig];
    
    
    self.adRequest = [MPNativeAdRequest requestWithAdUnitIdentifier:@"18a093da27674e308c90c94c3f605570" rendererConfigurations:configurations];
    
    
    MPNativeAdRequestTargeting *targeting = [MPNativeAdRequestTargeting targeting];
    targeting.desiredAssets = [NSSet setWithObjects:kAdIconImageKey, kAdCTATextKey, kAdTextKey, kAdTitleKey, nil];
    self.adRequest.targeting=targeting;
    __weak typeof(self) weakSelf = self;
    [self.adRequest startWithCompletionHandler:^(MPNativeAdRequest *request, MPNativeAd *response, NSError *error) {
        if (error) {
            NSLog(@"原生广告加载失败==========> %@", error);

        } else {
            NSLog(@"原生广告加载成功==========");
            weakSelf.nativeAd = response;
            weakSelf.nativeAd.delegate = weakSelf;
            [self showNative];

        }
    }];
}
- (void)dealloc{
    self.adRequest = nil;
}




- (void)showNative{
    [[self.viewContainner subviews] makeObjectsPerformSelector:@selector(removeFromSuperview)];
    UIView *adView=[self.nativeAd retrieveAdViewWithError:nil];
    adView.frame=self.viewContainner.bounds;
    [self.viewContainner addSubview:adView];
}


#pragma mark - MPNativeAdDelegate

- (void)willPresentModalForNativeAd:(MPNativeAd *)nativeAd
{
    NSLog(@"即将展示原生广告");
}

- (void)didDismissModalForNativeAd:(MPNativeAd *)nativeAd
{
    NSLog(@"关闭原生广告");
}

- (void)willLeaveApplicationFromNativeAd:(MPNativeAd *)nativeAd
{
    
}
- (UIViewController *)viewControllerForPresentingModalView
{
    return self.rootVC;
}

@end
